# -*- coding:utf-8 -*—


import json
import time

import pandas as pd
import os


def file_name(file_path):
    """
    获取每个文件的路径
    root 为当前目录路径
    dirs 为当前路径下所有子目录
    files 为当前路径下所有非目录子文件
    :param file_path:
    :return:
    """
    paths_list = []
    for root,dirs,files in os.walk(file_path):
        for file in files:
            path_list = os.path.join(root,file)
            paths_list.append(path_list)
    return paths_list

def json_out(file_path):
    """
    将json格式转换为xlsx格式
    :param path:
    :return:
    """
    exportPath = os.path.split(os.path.abspath(file_path))[0]
    now_time = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
    outname = "./json转txt" + now_time + ".xlsx"
    print(outname)
    # outputPath = exportPath + './json转excel.xlsx'
    outputPath = exportPath + outname
    with open(file_path, "r", encoding='utf-8') as f:
        data = json.load(f)
        # print(data)
    data = pd.DataFrame(data)
    data.to_excel(outputPath, index=None)

def json_outs(file_path):
    """
    将json格式转换为xlsx格式
    :param path:
    :return:
    """
    exportPath = os.path.split(os.path.abspath(file_path))[0]
    now_time =  time.strftime('%Y%m%d %H%M%S', time.localtime())
    outname="./json转txt"+now_time+".xlsx"
    print(outname)
    # outputPath = exportPath + './json转excel.xlsx'
    outputPath = exportPath + outname
    path_lists = file_name(file_path)
    list_data = []
    for path in path_lists:
        try:
            with open(path, "r", encoding='utf-8') as f:
                data = json.load(f)
                print(data)
                data = pd.DataFrame(data)
                list_data.append(data)
        except Exception as e:
            print("读取错误:",e)
    total_data = pd.concat(list_data)
    total_data.to_excel(outputPath, index=None)

if __name__ == '__main__':
    # file_path = "F:/json/玖天气象预报9月全月累积降雨（短期+中期+长期）第1个单元格左下角.json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\10月份预测数据\水文气象\玖天气象预报10月全月累积降雨（中期+长期）第1个单元格左下角.json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\9月预报数据对比\水文气象课题预测成果\导出数据3\玖天气象预报9月全月累积降雨（短期+中期+长期）.json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\10月份预测数据\水文气象\导出数据3\玖天气象预报10月全月累积降雨（中期+长期）.json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\10月份预测数据\水文气象\导出数据4\玖天气象预报10月全月累积降雨（中期+长期）(1).json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\9月预报数据对比\网格数据降雨值\202209.json"
    # file_path = r"F:\data\水电流域\2022.09.26预报数据对比\10月份预测数据\水文气象\导出数据4\玖天气象预报10月全月累积降雨（中期+长期）(2).json"
    file_path = r"F:\data\水电流域\2022.10.11全国行政区划修改\getStcdList.json"
    # json_outs(file_path)
    json_out(file_path)
